import {
    EditableProTable,
    ProCard,
    ProForm,
    ProFormDependency,
    ProFormList,
    ProFormText,
} from '@ant-design/pro-components';
import {CloseOutlined, PlusOutlined} from '@ant-design/icons';
import {Button, Col, message, Modal, Row, Upload, Typography, Form} from 'antd';
import React, {forwardRef, useEffect, useImperativeHandle, useRef, useState} from 'react';
import "./style.less";
import _ from 'lodash'
import {Logger} from "sass";
import {value} from "lodash/seq.js";
import {Decimal} from "decimal.js";

const {confirm} = Modal;
const {Text} = Typography;

const BASE_URL = import.meta.env.VITE_APP_BASE_API
const RSnetToken = sessionStorage.getItem('RSnetToken')

const getBase64 = (file) =>
    new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = (error) => reject(error);
    });

const cellData = (data, fields) => {
    fields.forEach((field, i) => {
        let count = 0;
        let indexCount = 1;
        try {
            while (indexCount < data.length) {
                let item = data.slice(count, count + 1)[0];
                if (!item.merge["rowSpan-" + i]) {
                    item.merge["rowSpan-" + i] = 1;
                }
                if (item[field] === data[indexCount][field]) {
                    item.merge["rowSpan-" + i]++;
                    item.merge.is = true;
                    item.merge.index = count;
                    data[indexCount].merge["rowSpan-" + i] = 0;
                } else {
                    count = indexCount;
                }
                indexCount++;
            }
        } catch {
        }
    })
    return data;
}


const convertValue = (skuData, dataSource) => {
    let skuColumns = [], result = [];
    // 根据SKU生成表头
    skuData.forEach((item, index) => {
        skuColumns.push({
            title: item.name,
            dataIndex: `sku-value-${index + 1}`,
            editable: false,
            onCell: (_, i) => {
                return {rowSpan: _.merge[`rowSpan-${index}`]};
            },
        })
    })

    // 根据SKU生成表格数据
    const recursive = (arr, index, obj) => {
        if (index === arr.length) {
            let currentData = {};
            let indexKey = '';
            for (const key in obj) {
                if (key.includes('value')) {
                    let objName = obj[key];
                    skuData.some(skuList => {
                        let a = skuList.itemName.findIndex(name => name.name === objName)
                        if (a !== -1) {
                            indexKey += a.toString()
                            return true
                        }
                    })
                }
            }
            let skuId = ''
            oldData.map(item => {
                if (item.key === indexKey) {
                    skuId = item.value
                }
            })
            const id = (Math.random() * 1000000).toFixed(0)
            if (dataSource) {
                dataSource.some((t, i) => {
                    if (t.skuId === skuId) {
                        currentData = t
                        // return true
                    } else {
                        if (!t.hasOwnProperty('skuId')) {
                            let flag = []
                            t.skuAttribute.some((k, j) => {
                                let dataKey = k.key, dataValue = k.value;
                                let SkuKey = obj[`sku-key-${j + 1}`];
                                let SkuValue = obj[`sku-value-${j + 1}`];
                                if (dataKey === SkuKey && dataValue === SkuValue) {
                                    flag.push(true)
                                }
                            })
                            if (flag.length === t.skuAttribute.length) {
                                currentData = t
                                // return true
                            }
                        }
                    }
                })
            }

            result.push({
                id,
                ...obj,
                ...currentData
            });
            return;
        }

        for (let item of arr[index].itemName) {
            recursive(arr, index + 1, {
                ...obj,
                [`sku-value-${index + 1}`]: item.name,
                [`sku-key-${index + 1}`]: arr[index].name,
                merge: {
                    is: false
                },
                // disabled: false
            });
        }
    };

    if (skuData.length) {
        recursive(skuData, 0, {});
    } else {
        result = []
    }

    result.map((item, index) => {
        let skuAttribute = []
        for (let i = 1; i <= skuColumns.length; i++) {
            skuAttribute.push({
                key: item[`sku-key-${i}`],
                value: item[`sku-value-${i}`],
            })
        }
        item.skuAttribute = skuAttribute
        item.merge = {is: false}
        return item
    })
    // 合并单元格
    cellData(result, skuColumns.map(item => item.dataIndex))
    return {
        result, skuColumns
    }
}
let first = true, oldData = [];
const uniqueKeyValues = (skuData, dataSource) => {
    oldData = []
    dataSource.forEach(i => {
        let str = '';
        i.skuAttribute.forEach((j) => {
            skuData.forEach(k => {
                k.itemName.forEach((w, index) => {
                    if (w.name === j.value) {
                        str += `${index}`
                    }
                })
            })
        })
        if (str !== '') {
            oldData.push({
                key: str,
                value: i.skuId
            })
        }
        // oldData[str] = i.skuId
    })
    first = false
}
const editTable = (skuData, editRef, formRef, mode, refresh) => {
    let dataSource = []
    if (formRef.current) {
        dataSource = formRef.current.getFieldValue('table')
    }
    if (mode === 'edit') {
        // dataSource = formRef.current.getFieldValue('table')
        if (first && dataSource !== undefined) {
            uniqueKeyValues(skuData, dataSource)
        }
    }
    let skuColumns = [], result = []
    // 防止频繁渲染导致卡顿
    if (refresh && first === (mode === 'add')) {
        let data = convertValue(skuData, dataSource);
        result = data.result
        skuColumns = data.skuColumns
    }

    // 上传图片条件限制
    const checkFileSize = (file, fileList) => {
        if (!['image/jpg', 'image/jpeg', 'image/png', 'image/webp', 'image/svg+xml'].includes(file.type)) {
            message.info(`上传文件格式不正确`)
            return Upload.LIST_IGNORE
        }
        if (file.size / 1024 / 1024 >= 5) {
            message.info(`上传文件大小最大为${5}MB`)
            return Upload.LIST_IGNORE
        }
    }
    // 上传之前处理格式
    const normFile = (e) => {
        if (e?.fileList.length) {
            return e?.fileList.map(item => {
                if (item.status === "done" && item.response) {
                    return item.response.data
                } else {
                    return item.url
                }
            }).toString();
        } else {
            return undefined
        }
    };
    // 上传之后处理回调格式
    const valueFile = (e) => {
        if (e) {
            return e?.split(',').map((item, index) => {
                return {
                    uid: `-${index + 1}`,
                    name: item.substring(item.lastIndexOf('/') + 1),
                    status: 'done',
                    url: item,
                }
            })
        } else {
            return []
        }
    }
    // 图片预览
    const handlePreview = async (file) => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj);
        }
        confirm({
            title: <Row>
                <Col flex="auto">{file.name || file.url.substring(file.url.lastIndexOf('/') + 1)}</Col>
                <Col flex="35px">
                    <Button onClick={() => Modal.destroyAll()} type="text" icon={<CloseOutlined/>}></Button>
                </Col>
            </Row>,
            icon: null,
            footer: null,
            width: 500,
            className: 'preview-container',
            content: <img
                alt="preview"
                style={{
                    width: '100%',
                }}
                src={file.url || file.preview}
            />,
        });
    }

    // 表格表头
    const columns = [
        ...skuColumns,
        {
            title: 'skuID',
            dataIndex: 'skuId',
            editable: false,
            hideInTable: true
        },
        {
            title: '划线价（元）',
            dataIndex: 'skuOriginalPrice',
            valueType: 'money',
            // initialValue: 0,
            fieldProps: () => {
                return {
                    min: 0,
                    style: {
                        width: "100%"
                    },
                    controls: false,
                    // changeOnBlur: false,
                }
            },
            formItemProps: () => {
                return {
                    getValueFromEvent: (args) => {
                        if (args === 0 || args === null){
                            return args
                        }else {
                            return Decimal(args).mul(100).toNumber() //乘
                        }
                    },
                    getValueProps: v => {
                        if (v!== null && !isNaN(v)){
                            return {
                                value: Decimal(v).div(100).toNumber() //除
                            }
                        }
                        else {
                            return {
                                value: null
                            }
                        }
                    },
                    rules: [
                        {
                            required: true,
                            validator: (_, value) => {
                                if(isNaN(value) || value === null){
                                    return Promise.reject(new Error('此项为必填项'));
                                }
                                return Promise.resolve();
                            }
                        },
                    ],
                };
            },
        },
        {
            title: '日常价（元）',
            dataIndex: 'skuCurrentPrice',
            valueType: 'money',
            // initialValue: 0,
            fieldProps: () => {
                return {
                    min: 0,
                    style: {
                        width: "100%"
                    },
                    controls: false,
                    // changeOnBlur: false
                }
            },
            formItemProps: () => {
                return {
                    getValueFromEvent: (args) => {
                        if (args === 0 || args === null){
                            return args
                        }else {
                            return Decimal(args).mul(100).toNumber() //乘
                        }
                    },
                    getValueProps: v => {
                        if (v!== null && !isNaN(v)){
                            return {
                                value: Decimal(v).div(100).toNumber() //除
                            }
                        }
                        else {
                            return {
                                value: null
                            }
                        }
                    },
                    rules: [
                        {
                            required: true,
                            validator: (_, value) => {
                                if(isNaN(value) || value === null){
                                    return Promise.reject(new Error('此项为必填项'));
                                }
                                return Promise.resolve();
                            }
                        },
                    ],
                };
            },
        },
        {
            title: '库存',
            dataIndex: 'skuStock',
            valueType: 'digit',
            width: 150,
            fieldProps: () => {
                return {
                    max: 99999,
                    precision: 0,
                    controls: false,
                    style: {
                        width: "100%"
                    }
                }
            },
            formItemProps: () => {
                return {
                    rules: [{required: true, message: '此项为必填项'}],
                };
            },
        },
        {
            title: '重量（kg）',
            dataIndex: 'skuWeight',
            valueType: 'digit',
            width: 150,
            min: 0,
            fieldProps: (_, config) => {
                return {
                    // defaultValue: 0.1,
                    precision: 1,
                    controls: false,
                    // disabled: config.entity.disabled,
                    style: {
                        width: "100%"
                    }
                }
            },
            formItemProps: () => {
                return {
                    getValueFromEvent: (args) => {
                        if (args === 0 || args === undefined){
                            return args
                        }else {
                            return args * 1000
                        }
                    },
                    getValueProps: v => {
                        if (v!== undefined && !isNaN(v)){
                            return {
                                value: v/ 1000
                            }
                        }
                        else {
                            return {
                                value: undefined
                            }
                        }
                    },
                    rules: [
                        {
                            required: true,
                            validator: (_, value) => {
                                if(isNaN(value) || value === undefined){
                                    return Promise.reject(new Error('此项为必填项'));
                                }
                                return Promise.resolve();
                            }
                        },
                    ],
                };
            },
        },
        {
            title: '描述',
            dataIndex: 'skuDescription',
            // formItemProps: () => {
            //     return {
            //         rules: [{required: true, message: '此项为必填项'}],
            //     };
            // },
        },
        {
            title: '图片',
            dataIndex: 'imageFile',
            formItemProps: (form, config) => {
                const flag = config.entity.imageFile
                return {
                    hasFeedback: true,
                    validateStatus: "error",
                    getValueFromEvent: normFile,
                    getValueProps: valueFile,
                    rules: [{
                        required: true,
                        message: '此项为必填项',
                    }]
                };
            },
            renderFormItem: (schema, config, form) => {
                let defaultFileList = [], images = config.record.imageFile;
                if (images) {
                    defaultFileList = [{
                        uid: `-1`,
                        name: images.substring(images.lastIndexOf('/') + 1),
                        status: 'done',
                        url: config.record.imageFile,
                    }]
                }
                return <Upload
                    action={BASE_URL + "management/oss/image/upload"}
                    listType="picture-card"
                    headers={{RSnetToken}}
                    beforeUpload={checkFileSize}
                    onPreview={handlePreview}
                    defaultFileList={defaultFileList}
                    disabled={false}
                >
                    {
                        config.record.imageFile !== undefined ? null : <div>
                            <PlusOutlined/>
                            <div style={{marginTop: 8}}>上传图片</div>
                        </div>
                    }
                </Upload>
            }
        },
        {
            title: '操作',
            valueType: 'option',
            hideInTable: mode === 'add' || result.length === 1 || skuColumns.length !== 1,
            render: () => {
                return null;
            },
        },
    ];
    // 删除
    const del = async (row) => {
        let i = row.index;
        // 接口返回可以删除后执行下面内容
        if (skuData.length === 1) {
            skuData[0].itemName.splice(i, 1);
            await uniqueKeyValues(skuData, dataSource)
            dataSource.splice(i, 1);
            formRef.current.setFieldsValue({
                productSkuJson: skuData,
                table: dataSource
            })
        }
    }
    return <EditableProTable
        loading={{
            spinning: !refresh,
            tip: "SKU规格编辑中"
        }}
        bordered={true}
        rowKey="id"
        value={result}
        toolBarRender={false}
        columns={columns}
        controlled={true}
        recordCreatorProps={false}
        editable={{
            form: editRef,
            type: 'multiple',
            editableKeys: result.map((item) => item.id),
            actionRender: (row, config, dom) => {
                return <Button type={'link'} onClick={() => del(row)} style={{margin: "0 auto"}}>删除</Button>;
            },
        }}
    />
}
const FunctionComponent = forwardRef((props, ref) => {

    const formRef = useRef();
    const [editRef] = Form.useForm();
    const [dataSource, setDataSource] = useState();
    const [flag, setFlag] = useState(true);

    const actionRef = useRef();

    useImperativeHandle(ref, () => ({
        formRef: formRef.current,
        editRef: editRef,
        getData
    }));
    useEffect(()=>{
        first = true
        oldData = []
    },[])
    const getData = () => {
        return dataSource
    }
    let mode = props.mode
    return (
        <>
            <ProForm
                onValuesChange={(change, allData) => {
                    let {result} = convertValue(allData.productSkuJson, allData.table);
                    setDataSource(result)
                }}
                formRef={formRef}
                validateTrigger="onBlur"
                initialValues={{
                    table: dataSource,
                    productSkuJson: []
                }}
                layout="horizontal"
                labelCol={{flex: "130px"}}
                wrapperCol={{span: 15}}
                submitter={{
                    // 配置按钮的属性
                    resetButtonProps: {
                        style: {
                            // 隐藏按钮
                            display: 'none',
                        },
                    },
                    submitButtonProps: {
                        style: {
                            // 隐藏按钮
                            display: 'none',
                        },
                    },
                }}
            >
                <ProFormList
                    actionRef={actionRef}
                    name="productSkuJson"
                    label="商品规格"
                    creatorButtonProps={mode === 'add' && {
                        creatorButtonText: '添加规格项',
                    }}
                    min={1}
                    max={3}
                    copyIconProps={false}
                    itemRender={({listDom, action}, {index}) => (
                        <ProCard
                            bordered
                            style={{marginBlockEnd: 8}}
                            title={`规格${index + 1}`}
                            extra={mode === 'add' && action}
                            bodyStyle={{paddingBlockEnd: 0}}
                        >
                            {listDom}
                        </ProCard>
                    )}
                    creatorRecord={{name: undefined, itemName: [{name: undefined}]}}
                    rules={[{required: true, message: '请输入商品规格'}]}
                    extra={<Text type="danger">*修改商品规格将会清空规格设置</Text>}
                    actionGuard={{
                        beforeAddRow: async (defaultValue, insertIndex, count) => {
                            let fileArr = [], arr = actionRef.current?.getList();
                            arr.forEach((item, index) => {
                                if (item.name || item.name === undefined) {
                                    fileArr.push(['productSkuJson', index, 'name'])
                                }
                                item.itemName.forEach((j, k) => {
                                    if (j.name || j.name === undefined) {
                                        fileArr.push(['productSkuJson', index, 'itemName', k, 'name'])
                                    }
                                })
                            })

                            return new Promise((resolve) => {
                                if (arr.length === 0) {
                                    resolve(true)
                                } else {
                                    formRef.current.validateFields([...fileArr]).then((res) => {
                                        setTimeout(() => resolve(true), 200);
                                    })
                                        .catch(errorInfo => {
                                            resolve(false)
                                        })
                                }
                            });
                        }
                    }}
                >
                    {(f, index, action) => {
                        return (
                            <>
                                <ProFormText
                                    style={{padding: 0}}
                                    width="md"
                                    name="name"
                                    fieldProps={{
                                        maxLength: 100,
                                        showCount: true
                                    }}
                                    formItemProps={{
                                        onFocus: () => {
                                            setFlag(false)
                                        },
                                        onBlur: () => {
                                            setFlag(true)
                                        }
                                    }}
                                    label={"规格名"}
                                    rules={[
                                        {
                                            required: true,
                                        },
                                        {
                                            validator: async (_, value) => {
                                                const row = actionRef.current?.getList();
                                                if (!value || row.filter(item => item.name === value).length === 1) {
                                                    return Promise.resolve();
                                                }
                                                return Promise.reject('该规格名已存在!');
                                            },
                                        }
                                    ]}
                                />
                                <ProForm.Item isListField style={{marginBlockEnd: 0}} label="">
                                    <ProFormList
                                        label={'规格值'}
                                        name="itemName"
                                        creatorButtonProps={{
                                            creatorButtonText: '添加',
                                            icon: false,
                                            // type: 'link',
                                            style: {width: 'unset'},
                                        }}
                                        min={1}
                                        copyIconProps={false}
                                        deleteIconProps={{tooltipText: '删除'}}
                                        creatorRecord={{name: undefined}}
                                        itemRender={({listDom, action}) => (
                                            <div
                                                style={{
                                                    display: 'inline-flex',
                                                    marginInlineEnd: 25,
                                                }}
                                            >
                                                {listDom}
                                                {mode === 'add' && action}
                                            </div>
                                        )}
                                        rules={[{required: true}]}
                                        actionGuard={{
                                            beforeAddRow: async (defaultValue, insertIndex, count) => {
                                                return new Promise((resolve) => {
                                                    formRef.current.validateFields(
                                                        [
                                                            ['productSkuJson', index, 'name'],
                                                            ['productSkuJson', index, 'itemName', insertIndex - 1, 'name']
                                                        ]
                                                    ).then((res) => {
                                                        setTimeout(() => resolve(true), 200);
                                                    })
                                                        .catch(errorInfo => {
                                                            resolve(false)
                                                        })
                                                });
                                            }
                                        }}
                                    >
                                        <ProFormText
                                            rules={
                                                [
                                                    {
                                                        required: true,message:'请输入规格值'
                                                    },
                                                    {
                                                        validator: async (_, value) => {
                                                            const row = actionRef.current?.getList();
                                                            const items = row[Number(_.field.split('.')[1])].itemName;
                                                            if (!value || items.filter(item => item.name === value).length === 1) {
                                                                return Promise.resolve();
                                                            }
                                                            return Promise.reject('该规格值已存在!');
                                                        },
                                                    }
                                                ]
                                            }
                                            formItemProps={{
                                                onFocus: () => {
                                                    setFlag(false)
                                                },
                                                onBlur: () => {
                                                    setFlag(true)
                                                }
                                            }}
                                            allowClear={false}
                                            width="xs"
                                            name={['name']}
                                        />
                                    </ProFormList>
                                </ProForm.Item>
                            </>
                        )
                    }}
                </ProFormList>
                <ProFormDependency name={['productSkuJson']}>
                    {({productSkuJson}) => {
                        return <ProForm.Item
                            label="规格设置"
                            name="table"
                            wrapperCol={{span: 21}}
                            rules={[{required: true}]}
                        >
                            {editTable(productSkuJson, editRef, formRef, mode, flag)}
                        </ProForm.Item>
                    }}
                </ProFormDependency>
            </ProForm>
        </>
    );
});

export default FunctionComponent;
